'use strict';
const fiip = require('fiip');
const Link = fiip.Link;

const startClient = (ip, port) => {
  const net = require('net');
  const rlink = new Link.Client();
  rlink.type = Link.type.tcp;
  rlink.status = Link.status.client;
  rlink.address = ip;
  rlink.port = port;
  rlink.fd = net.createConnection(port, ip);
  rlink.send = (data, dataLen, link) => {
    rlink.fd.write(data.slice(0, dataLen));
  };
  rlink.recv = fiip.recv.bind(fiip);

  rlink.fd.on('data', (data) => {
    rlink.recv(data, data.length, rlink);
  });
  rlink.fd.on('error', (error) => {
    console.error('fiip-link-tcp/client: error:', error);
  });
  rlink.fd.on('close', () => {
    console.error('fiip-link-tcp/client: close');
  });

  return rlink;
};

module.exports = startClient;
